using UnityEngine;
using UnityEngine.UI;
namespace Share
{
    public class ImageFlip : MonoBehaviour
    {
        [SerializeField]
        Image m_Image;
        [SerializeField]
        float m_fSpeed = 1;

        public float Speed
        {
            get { return m_fSpeed; }
            set { m_fSpeed = value; }
        }

        private float m_TargetDir = 1f;
        private float m_CurrentDir = 1f;
        private float m_Progress = 0f;
        private Quaternion m_CurrentRot = Quaternion.identity;

        public float Dir
        {
            get
            {
                return m_TargetDir;
            }
        }
        void Start()
        {
            if (m_Image == null)
                m_Image = GetComponent<Image>();
        }

        /// <summary>
        /// 设置图片翻转方向
        /// </summary>
        /// <param name="left">左方向值</param>
        /// <param name="right">右方向值</param>
        public void DoFlip(int left, int right)
        {
            // 将方向转换为角度
            if (left < right)
                m_TargetDir = 180f;
            else if (left > right)
                m_TargetDir = 0f;
            else
                m_TargetDir = 90f;
        }

        void Update()
        {
            if (m_Image == null) return;

            // 计算当前方向
            if (m_Progress < 1f && m_fSpeed > 0)
            {
                m_Progress += Time.deltaTime / m_fSpeed;
                m_Progress = Mathf.Clamp01(m_Progress);

                // 使用角度插值计算当前方向
                m_CurrentDir = Mathf.LerpAngle(m_CurrentDir, m_TargetDir, m_Progress);
            }
            else
            {
                m_CurrentDir = m_TargetDir;
            }

            // 应用平滑旋转
            Quaternion targetRot = Quaternion.Euler(0, 0, m_CurrentDir);
            m_CurrentRot = Quaternion.Lerp(m_CurrentRot, targetRot, Time.deltaTime * m_fSpeed);
            m_Image.transform.localRotation = m_CurrentRot;
        }
    }
}
